#include "usbthread.h"
#include "mainwindow.h"

#include <iostream>

USBThread::USBThread(QObject *parent) : QThread(parent)
{
    status = USB_DISCONNECT;

    usb_write_length = 0;

    thread_stop = false;

    report_id = DEFAULT_REPORT_ID;

    hid_init();  // 这一句可要可不要

    tick = QDateTime::currentMSecsSinceEpoch();


}

QList<HidDeviceInfo> USBThread::get_device_list()
{
    QList<HidDeviceInfo> hid_device_list;
    struct hid_device_info * hid_device_infos =  hid_enumerate(vid,pid);
    if(hid_device_infos == NULL)
        return hid_device_list;
    while(hid_device_infos != NULL)
    {
        hid_device_list.push_back(HidDeviceInfo(hid_device_infos));
        qDebug() << sizeof(hid_device_infos->serial_number);
        qDebug() << QString::fromWCharArray(hid_device_infos->serial_number);
        qDebug() << HidDeviceInfo(hid_device_infos);
        hid_device_infos = hid_device_infos->next;
    }
    hid_free_enumeration(hid_device_infos);
    return hid_device_list;
}

bool USBThread::open_usb(QString usb_path)
{
    status = USB_DISCONNECT;
    usbthread_handle = hid_open_path(usb_path.toLocal8Bit().constData());
    qDebug() << usbthread_handle;
    if(usbthread_handle != NULL)
    {
        status = USB_CONNECT;

//        wchar_t wchar_str[64];
//        hid_get_product_string(usbthread_handle,wchar_str,64);
//        qDebug()<<QString::fromWCharArray(wchar_str);
        emit usb_connect(QString(" "));
//        hid_get_serial_number_string(usbthread_handle,wchar_str,64);
//        qDebug()<<QString::fromWCharArray(wchar_str);
        thread_pause = false;
        return true;
    }
    else
        return false;
}

//继续接收
void USBThread::continue_thread()
{
    thread_pause = false;
}

//暂停接收
void USBThread::pause_thread()
{

    //thread_pause = true;

    //关闭USB
    if(status == USB_CONNECT){
        qDebug()<<"hid_close";
        hid_close(usbthread_handle);
        qDebug()<< usbthread_handle;
        usbthread_handle = NULL;
    }
    status = USB_DISCONNECT;
    emit usb_disconnect();
}

//停止线程
void USBThread::stop_thread()
{
    thread_stop = true;
}

//发送数据
//void USBThread::send_data(unsigned char *data, size_t length)
void USBThread::send_data(const QByteArray & data)
{

//    if(status == USB_CONNECT)
//    {
//        unsigned char send_buf[65];
//        int i;
//        for(i=0;i<65;i++)
//        {
//            send_buf[i] = i;
//        }
//        send_buf[0] = 0x00;
//        int res = hid_write(usbthread_handle,send_buf,65);
//        qDebug()<<QString::number(res);
//        emit send_num(USB_MAX_DATA_LENGTH);
//    }return;

    if(status != USB_CONNECT)
        return;    
    QByteArray buffer(data);
    buffer.prepend(report_id);
    int res = hid_write(usbthread_handle, (const unsigned char *)buffer.data(), buffer.size());
    /*
    //发送1+64字节数据,下位机接收并处理后64字节
    unsigned char send_buf[USB_MAX_DATA_LENGTH+1] = {0};
    int i=0;
    int res;

    for(i=0;i<USB_MAX_DATA_LENGTH+1;i++)
        send_buf[i] = 0;

    memcpy(send_buf+1,data.data(),data.length()>USB_MAX_DATA_LENGTH?USB_MAX_DATA_LENGTH:data.length());

    send_buf[0] = report_id;     //第一字节是REPORT ID,固定不变


    res = hid_write(usbthread_handle,send_buf,(size_t)USB_MAX_DATA_LENGTH+1);   //发送REPORT+64字节数据
    */

    if(res < buffer.size())
    {
        qDebug()<<QString::number(res);
        /* res=-1表示发送失败  res=0表示发送数为0 */
        emit usb_send_error();
        return;
    }
    return;
}

_USB_STATUS USBThread::get_usbstatus()
{
    return status;
}

void USBThread::run()
{
    while(!thread_stop)
    {
        if(!thread_pause)
        {
            switch(status)
            {
                case USB_CONNECT:
                {
                    //int res = hid_get_feature_report(usbthread_handle,usb_read_data,USB_MAX_DATA_LENGTH);
                    int res = hid_read_timeout(usbthread_handle,usb_read_data,USB_MAX_DATA_LENGTH, 2000);
                    //int res = hid_read(usbthread_handle,usb_read_data,8);
                    if(res > 0)
                    {
                        //qDebug() << "res:" << res;
                        emit new_data(QByteArray((char *)usb_read_data, res));
                    }
                    else if(res == 0)
                    {

                    }
                    else
                    {
                       // qDebug() << QDateTime::currentMSecsSinceEpoch() - tick;
                        if(QDateTime::currentMSecsSinceEpoch() - tick < 500 )
                            break;

                        tick = QDateTime::currentMSecsSinceEpoch();
                        wchar_t str[16];
                        int res;
                        res = hid_get_serial_number_string(usbthread_handle,str,16);
                        qDebug() << "hid_get_serial_number_string:" << res;
                        if(res == 0)
                        {
                           status = USB_DISCONNECT;
                           emit usb_disconnect();
                        }
                    }
                }
                    break;
                case USB_DISCONNECT:
                {
                    msleep(100);
//                    /* USB未连接的时候,对实时性要求并不高,避免浪费CPU */
//                    if(QDateTime::currentMSecsSinceEpoch() - tick < 500 )
//                        break;

//                    tick = QDateTime::currentMSecsSinceEpoch();

//                    usbthread_handle = hid_open(vid,pid,NULL);
//                    if(usbthread_handle != NULL)
//                    {
//                        qDebug()<<"USB设备打开成功";
//                        status = USB_CONNECT;

//                        wchar_t wchar_str[64];
//                        hid_get_product_string(usbthread_handle,wchar_str,64);
//                        qDebug()<<QString::fromWCharArray(wchar_str);
//                        emit usb_connect(QString::fromWCharArray(wchar_str));
//                    }
                }
                    break;
                default:
                    break;
            }
        }
    }
    hid_exit();
    quit();
}

